package com.example.dbsample.config.database;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * TODO 不太确定这个是干啥的，暂时加上
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.ARRAY)
public class MyBatisVarcharArrayTypeHandler extends BaseTypeHandler<String[]> {
    private static final String TYPE_NAME_VARCHAR = "varchar";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter,
                                    JdbcType jdbcType) throws SQLException {
        Connection conn = ps.getConnection();
        Array array = conn.createArrayOf(TYPE_NAME_VARCHAR, parameter);
        ps.setArray(i, array);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getArray(rs.getString(columnName));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getArray(rs.getString(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getArray(cs.getString(columnIndex));
    }

    /**
     * 该方法是把在mapper.xml里面配置了typeHandler=MyArrayTypeHandler的字段
     * 走我们这个自定义方法来实现字符串转字符串数组
     * 同理，我们可以把它转成任何我们想转的格式，如Json
     */
    private String[] getArray(String value) {
        if(StringUtils.isBlank(value)) {
            return null;
        }
        JSONArray array = JSON.parseArray(value);
        return null == array ? null : (String[]) array.toArray(new String[0]);

    }
}
